using WinformTemplete.Models;
using WinformTemplete.Modules.Blog.Models;
using Microsoft.Extensions.Configuration;
using SqlSugar;

namespace WinformTemplete.Common
{
    public class DatabaseManager
    {
        private static SqlSugarClient _instance;
        private static readonly object _lock = new object();

        public static SqlSugarClient GetInstance(string connectionString = null)
        {
            if (_instance == null)
            {
                lock (_lock)
                {
                    if (_instance == null)
                    {
                        var configuration = new ConfigurationBuilder()
                            .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                            .Build();

                        connectionString = connectionString ?? configuration.GetConnectionString("DefaultConnection");

                        _instance = new SqlSugarClient(new ConnectionConfig()
                        {
                            ConnectionString = connectionString,
                            DbType = DbType.Sqlite,
                            IsAutoCloseConnection = true,
                            InitKeyType = InitKeyType.Attribute
                        });
                        _instance.Aop.OnLogExecuting = (sql, parameters) =>
                        {
                            Console.WriteLine(sql);
                        };
                        _instance.DbMaintenance.CreateDatabase(); //建库
                        _instance.CodeFirst.InitTables<BlogModel>(); //所有库都支持 
                    }
                }
            }
            return _instance;
        }
    }
} 